package com.heima.user.interceptor;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 新增拦截器
 */
@Slf4j
public class AppTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 从请求头中获取用户id
        String userId = request.getHeader("userId");
        System.out.println("拦截器获取到的userId======"+userId);
        //2. 判断是否获取到了 如果获取到了则存储到当前线程的ThreadLocal对象中 给后面的 c s d模块使用
        if(StringUtils.isNotEmpty(userId)){
            ApUser apUser = new ApUser();
            apUser.setId(Integer.parseInt(userId));
            AppThreadLocalUtil.setUser(apUser);
        }

        return true;
    }

    /**
     * 清理线程本地变量
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler the handler (or {@link }) that started asynchronous
     * execution, for type and/or instance examination
     * @param modelAndView the {@code ModelAndView} that the handler returned
     * (can also be {@code null})
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("清理threadlocal");
        AppThreadLocalUtil.clear();
    }
}
